import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';

interface User {
  id: number;
  name: string;
  email: string;
  status: number;
}

@Component({
  selector: 'app-admin-user',
  templateUrl: './admin-user.component.html',
  styleUrls: ['./admin-user.component.css']
})

export class AdminUserComponent implements OnInit {

  users: any;
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: ReadonlyArray<User> = [];
  setOfCheckedId = new Set<number>();

  constructor(private http: HttpClient, private router: Router) {
  }

  ngOnInit(): void {
    this.getAllUser();
  }

  getAllUser(): void {
    const url = '/api/adminUser/getAllUser';
    this.http.get(url).subscribe((resp: any) => {
      const code = resp.code;
      if (code === 200) {
        this.users = resp.data;
      }
    }, (error: any) => {
      if (error.status === 403) {
        this.router.navigateByUrl('/permision-error');
      }
    });
  }

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    console.log(this.listOfCurrentPageData);
    this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: ReadonlyArray<User>): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    this.checked = this.listOfCurrentPageData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.listOfCurrentPageData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
}
